package com.zhaolin.contorller;

import com.zhaolin.entity.Question;
import com.zhaolin.entity.Survey;
import com.zhaolin.service.QuestionService;
import com.zhaolin.service.SurveyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

@Controller
@CrossOrigin
public class DynamicController {

    @Autowired
    SurveyService surveyService;

    @Autowired
    QuestionService questionService;

    @GetMapping("/diy/{uuid}")
    public String preview(@PathVariable("uuid")String uuid, ModelMap modelMap){
        //先查出所有执行中的问卷
        Survey survey = new Survey();
        survey.setState(Survey.state_exec);
        List<Survey> query = surveyService.queryAll(survey);
        Survey entity = null;
        for (Survey num:query) {
            //判断集合里的 Url是否为空 并且 查看URL里是否含有uuid
            if (num.getUrl()!=null && num.getUrl().contains(uuid)){
                //将含有uuid的对象装到 entity里去
                entity=num;
            }
        }
        //判断entity是否有值
        if (entity == null){
            //没有值跳到失败页面
            modelMap.addAttribute("msg","你要访问的问卷已过期或不存在");
            return "page/error";
        }else{
            //有值的话就通过entity的id查询所有的问卷
            Question question = new Question();
            question.setSurveyId(entity.getId());
            List<Question> query1 = questionService.query(question);
            //将问题设置为survey的属性
            entity.setQuestions(query1);
            modelMap.addAttribute("survey",entity);
            return "page/survey/exec";
        }

    }

    @GetMapping("/dy/success")
    public String success(){
        return "page/survey/success";
    }


}
